import httplib
import urllib


class VirtuosoManager:
    def __init__(self, host, user='', password=''):
        self.host = host
        self.user = user
        self.password = password

    def get_request(self, params={}, headers={}):
        host_array = self.host.split('/')
        print host_array
        if host_array[0].startswith('http:'):
            url = ''
            array_len = len(host_array)
            for i in range(2, len(host_array) - 1):
                url = url + host_array[i]
            conn = httplib.HTTPConnection(url)
            conn.request("GET", '/' + host_array[len(host_array) - 1] + '?' + urllib.urlencode(params), "", headers)
        else:
            url = ''
            for i in range(0, len(host_array) - 1):
                url = url + host_array[i]
            conn = httplib.HTTPConnection(url)
            conn.request("GET", '/' + host_array[len(host_array) - 1] + '?' + urllib.urlencode(params), "", headers)

        response = conn.getresponse()
        data = response.read()
        return data

    def select(self, query, accept):
        params = {'query': query}
        headers = {"Accept": accept}
        return self.get_request(params, headers)

    def update(self, query, graph):
        params = {'query': query, 'default-graph-uri': graph}
        return self.get_request(params=params)
